package com.tiancheng.trade.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiancheng.trade.commom.core.utils.JsonUtil;
import com.tiancheng.trade.commom.core.enums.SettleStatusEnum;
import com.tiancheng.trade.payment.mapper.SettleDetailMapper;
import com.tiancheng.trade.payment.model.SettleDetail;
import com.tiancheng.trade.payment.service.SettleDetailService;
import com.tiancheng.trade.payment.task.ums.bo.SettleDetailBo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author kellen
 * @date 2024-12-09 17:04
 */
@Slf4j
@Service
public class SettleDetailServiceImpl implements SettleDetailService {
    @Autowired
    private SettleDetailMapper settleDetailMapper;

    /**
     * 批量插入
     *
     * @param details
     * @return
     */
    public Integer saveBatch(List<SettleDetail> details) {
        return settleDetailMapper.insertBatch(details);
    }

    /**
     * 根据id、apprFileName、apprId、distFileName、distId组合条件批量更新
     *
     * @param submitBOS
     * @return
     */
    public Integer updateBatch(List<SettleDetailBo> submitBOS) {
        return settleDetailMapper.updateBatch(submitBOS);
    }

    @Override
    public Integer updatePayFlowSettleStatus(List<SettleDetailBo> settleDetailBos) {
        Set<String> detailIds = settleDetailBos.stream().map(SettleDetailBo::getApprId).collect(Collectors.toSet());
        QueryWrapper<SettleDetail> conditions = new QueryWrapper<>();
        conditions.in("appr_id", detailIds);
        conditions.eq("appr_status", SettleStatusEnum.ING.getCode());
        List<SettleDetail> settleDetails = settleDetailMapper.selectList(conditions);
        if (!CollectionUtils.isEmpty(settleDetails)) {
            // 查询到所有需要更改状态的明细记录
            List<String> collect = settleDetails.stream().map(SettleDetail::getApprId).collect(Collectors.toList());
            List<String> successCollect = settleDetailBos.stream().filter(settleDetailBo -> settleDetailBo.getApprStatus().equals(SettleStatusEnum.SUCCESS.getCode()))
                    .map(SettleDetail::getApprId).collect(Collectors.toList());
            List<String> failCollect = settleDetailBos.stream().filter(settleDetailBo -> settleDetailBo.getApprStatus().equals(SettleStatusEnum.FAIL.getCode()))
                    .map(SettleDetail::getApprId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(successCollect)) {
                successCollect.retainAll(collect);
                if (!CollectionUtils.isEmpty(successCollect)) {
                    log.info("更新支付流水为划付成功状态,分账id：{}", JsonUtil.toJsonString(successCollect));
                    settleDetailMapper.updatePayFlowBatch(successCollect, "SUCCESS");
                    settleDetailMapper.updateRefundFlowBatch(successCollect, "SUCCESS");
                }
            }
            if (!CollectionUtils.isEmpty(failCollect)) {
                failCollect.retainAll(collect);
                if (!CollectionUtils.isEmpty(failCollect)) {
                    log.info("更新支付流水为划付失败状态,分账id：{}", JsonUtil.toJsonString(failCollect));
                    settleDetailMapper.updatePayFlowBatch(failCollect, "ERROR");
                    settleDetailMapper.updateRefundFlowBatch(failCollect, "ERROR");
                }
            }
            return 1;
        }
        return 0;
    }

    @Override
    public void setApprAndDistError(String apprFileName) {
        QueryWrapper<SettleDetail> conditions = new QueryWrapper<>();
        conditions.eq("appr_file_name", apprFileName);
        List<SettleDetail> settleDetails = settleDetailMapper.selectList(conditions);
        if(CollectionUtils.isEmpty(settleDetails)){
            log.error("未查询到划付文件：{}的明细",apprFileName);
            return;
        }
        List<SettleDetailBo> updateDetails=new ArrayList<>(settleDetails.size());
        for (SettleDetail settleDetail : settleDetails) {
            SettleDetailBo adb = new SettleDetailBo();
            adb.setId(settleDetail.getId());
            adb.setApprFileName(apprFileName);
            adb.setApprId(settleDetail.getApprId());//划付指令ID
            adb.setSucAmount(0L);

            adb.setDistStatus(SettleStatusEnum.FAIL.getCode());
            adb.setDistFailReason("手动设置失败");
            adb.setApprStatus(SettleStatusEnum.FAIL.getCode());
            adb.setApprFailReason("手动设置失败");
            updateDetails.add(adb);
        }
        settleDetailMapper.updateBatch(updateDetails);
        log.info("更新{}明细完成,开始更新支付、退款流水状态",apprFileName);
        List<String> failCollect = updateDetails.stream().filter(settleDetailBo -> settleDetailBo.getApprStatus().equals(SettleStatusEnum.FAIL.getCode()))
                .map(SettleDetail::getApprId).collect(Collectors.toList());

        settleDetailMapper.updatePayFlowBatchError(failCollect);
        settleDetailMapper.updateRefundFlowBatchError(failCollect);
        log.info("更新{}更新支付、退款流水状态完成",apprFileName);
    }
}
